package com.aek.aekdroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.aek.aekdroid.data.IDbConstants;
import com.aek.aekdroid.data.MatchData;

public class ShowMatchActivity extends BaseActivity {
	public static final String TAG = "ShowMatchActivity";
	public static final String PLAYER_NAME = "player";
	private int match_id;
	private TextView tournament;
	private TextView datetime;
	private TextView stadium;
	private TextView homeTeam;
	private TextView awayTeam;
	private TextView homeGoals;
	private TextView awayGoals;
	private String matchFullTitle = "";
	private ListView detailsList;
	private ListView playersList;
	private ToggleButton toggleButton;
	private TextView toggleLabel;
	private TextView emptyDetails;
	private TextView emptyEleven;
	private LinearLayout toggleLayout;
	private Cursor cursor;
	private SimpleCursorAdapter detailsAdapter;
	private SimpleAdapter playersAdapter;
	private boolean isDetailsEmpty;
	private boolean isElevenEmpty;
	static final String[] DETAILS_FROM = { MatchData.DETAILS_C_TYPE, MatchData.DETAILS_C_COMMENT, MatchData.DETAILS_C_MIN,
			MatchData.DETAILS_C_PLAYER, MatchData.DETAILS_C_TYPE };
	static final int[] DETAILS_TO = { R.id.detailIcon, R.id.detailComment, R.id.detailMin, R.id.detailPlayer, R.id.detailIconAway };
	static final String[] PLAYERS_FROM = { PLAYER_NAME };
	static final int[] PLAYERS_TO = { R.id.player_name };
	private static int line;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_match);
		this.match_id = getIntent().getIntExtra(IDbConstants.MATCHES_C_ID, 0);
		MyLog.d(TAG, "match id" + this.match_id);
		this.init();
		this.line = -1;
		MyLog.d(TAG, "onCreate");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.removeItem(R.id.menu_update);
		menu.removeItem(R.id.menu_purge);
		menu.removeItem(R.id.menu_checkUpdate);
		return true;
	}

	private void init() {
		homeTeam = (TextView) findViewById(R.id.show_match_homeTeam);
		awayTeam = (TextView) findViewById(R.id.show_match_awayTeam);
		homeGoals = (TextView) findViewById(R.id.show_match_homeGoals);
		awayGoals = (TextView) findViewById(R.id.show_match_awayGoals);
		stadium = (TextView) findViewById(R.id.show_match_stadium);
		datetime = (TextView) findViewById(R.id.show_match_datetime);
		tournament = (TextView) findViewById(R.id.show_match_tournament);
		emptyDetails = (TextView) findViewById(R.id.show_match_emptyDetails);
		emptyEleven = (TextView) findViewById(R.id.show_match_emptyEleven);
		detailsList = (ListView) findViewById(R.id.show_match_listDetails);
		playersList = (ListView) findViewById(R.id.show_match_listPlayers);
		toggleButton = (ToggleButton) findViewById(R.id.show_match_toggleButton);
		toggleLabel = (TextView) findViewById(R.id.show_match_toggleLabel);
		toggleLayout = (LinearLayout) findViewById(R.id.show_match_toggleLine);
		togglePlayers(toggleButton);
	}

	@Override
	public void onBackPressed() {
		Intent scheduleActivity = new Intent(this, ScheduleActivity.class);
		scheduleActivity.putExtra(IDbConstants.MATCHES_C_ID, match_id);
		startActivity(scheduleActivity);
	}

	private void setUpMatch() {
		cursor = aek.getMatchData().getMatch(this.match_id);

		if (cursor.getCount() == 0) {
			cursor.close();
			return;
		}

		cursor.moveToFirst();
		// startManagingCursor(cursor);
		homeTeam.setText(cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_HOME_TEAM)));
		homeGoals.setText(cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_HOME_GOALS)));
		awayTeam.setText(cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_AWAY_TEAM)));
		awayGoals.setText(cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_AWAY_GOALS)));
		stadium.setText(cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_STADIUM)));
		long d = cursor.getLong(cursor.getColumnIndex(IDbConstants.MATCHES_C_DATETIME));
		datetime.setText(Helper.createDate(d));
		tournament.setText(cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_TOURNAMENT)));
		matchFullTitle = homeTeam.getText() + "-" + awayTeam.getText() + "=" + homeGoals.getText() + "-" + awayGoals.getText();
		// GET PLAYERS
		String players = cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_PLAYERS));
		if (players != null && !players.equals("")) {
			String[] playersArr = players.split(",");
			if (playersArr.length == 0) {
				// toggleButton.setVisibility(toggleLayout.GONE);
				emptyEleven.setVisibility(View.VISIBLE);
				isElevenEmpty = true;
			} else {
				List<Map<String, String>> playersData = createList(playersArr);
				playersAdapter = new SimpleAdapter(this, playersData, R.layout.player, PLAYERS_FROM, PLAYERS_TO);
				playersList.setAdapter(playersAdapter);
				emptyEleven.setVisibility(View.GONE);
				isElevenEmpty = false;
			}
		} else {
			emptyEleven.setVisibility(View.GONE);
			isElevenEmpty = true;
		}
		// GET DETAILS
		// stopManagingCursor(cursor);
		cursor.close();
		cursor = aek.getMatchData().getMatchDetails(this.match_id);
		if (cursor.getCount() > 0) {
			isDetailsEmpty = false;
			emptyDetails.setVisibility(View.GONE);
		} else {
			isDetailsEmpty = true;
			emptyDetails.setVisibility(View.VISIBLE);
		}
		// startManagingCursor(cursor);
		// Setup Adapter
		detailsAdapter = new SimpleCursorAdapter(this, R.layout.detail, cursor, DETAILS_FROM, DETAILS_TO);
		detailsAdapter.setViewBinder(new DetailsBinder());
		detailsList.setAdapter(detailsAdapter);

	}

	private List<Map<String, String>> createList(String[] playersArr) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (int i = 0; i < playersArr.length; i++) {
			Map<String, String> m = new HashMap<String, String>();
			m.put(PLAYER_NAME, (i + 1) + ". " + playersArr[i]);
			list.add(m);
		}
		return list;

	}

	public void togglePlayers(View view) {
		ToggleButton toggle = (ToggleButton) view;
		if (toggle.isChecked()) {
			playersList.setVisibility(ListView.VISIBLE);
			detailsList.setVisibility(ListView.GONE);
			emptyDetails.setVisibility(View.GONE);
			emptyEleven.setVisibility(isElevenEmpty ? View.VISIBLE : View.GONE);
			toggleLabel.setText(R.string.startingEleven);
			toggle.setBackgroundResource(R.drawable.toggle_details);
		} else {
			playersList.setVisibility(ListView.GONE);
			emptyEleven.setVisibility(View.GONE);
			emptyDetails.setVisibility(isDetailsEmpty ? View.VISIBLE : View.GONE);
			detailsList.setVisibility(ListView.VISIBLE);
			toggleLabel.setText(R.string.titleShowMatch);
			toggle.setBackgroundResource(R.drawable.toggle_players);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.setUpMatch();
		if (aek.isAdmin()) {
			MyLog.d(TAG, "Register context menu");
			registerForContextMenu(detailsList);
			registerForContextMenu(playersList);
			registerForContextMenu(emptyDetails);
			registerForContextMenu(emptyEleven);
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		cursor.close();
		if (aek.isAdmin()) {
			unregisterForContextMenu(detailsList);
			unregisterForContextMenu(playersList);
			unregisterForContextMenu(emptyDetails);
			unregisterForContextMenu(emptyEleven);
		}
		// aek.getMatchData().close();
	}

	@Override
	protected void onDestroy() {
		cursor.close();
		super.onDestroy();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (aek.isAdmin()) {
			super.onCreateContextMenu(menu, v, menuInfo);
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.match_menu, menu);
			if (v.getId() == R.id.show_match_emptyDetails) {
				menu.removeItem(R.id.match_menu_editDetail);
				menu.removeItem(R.id.match_menu_startingEleven);
			} else if (v.getId() == R.id.show_match_emptyEleven || v.getId() == R.id.show_match_listPlayers) {
				menu.removeItem(R.id.match_menu_editDetail);
				menu.removeItem(R.id.match_menu_createDetail);
			} else if (v.getId() == R.id.show_match_listDetails || v.getId() == R.id.show_match_listPlayers) {
				menu.removeItem(R.id.match_menu_startingEleven);
			}

		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int _id = -1;
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		if (item.getItemId() == R.id.match_menu_editDetail && info != null) {
			Cursor detail = (Cursor) detailsList.getItemAtPosition(info.position);
			_id = detail.getInt(detail.getColumnIndex(IDbConstants.DETAILS_C_ID));
			detail.close();
		}
		if (item.getItemId() == R.id.match_menu_createDetail) {
			Intent addDetailsIntent = new Intent(this, AddDetailsActivity.class);
			addDetailsIntent.putExtra(AddDetailsActivity.MATCH_ID, match_id);
			addDetailsIntent.putExtra(AddDetailsActivity.MATCH, matchFullTitle);
			addDetailsIntent.putExtra(AddDetailsActivity.DETAIL_ID, _id);
			startActivity(addDetailsIntent);
			return true;
		} else if (item.getItemId() == R.id.match_menu_editDetail) {
			Intent editDetailsIntent = new Intent(this, AddDetailsActivity.class);
			editDetailsIntent.putExtra(AddDetailsActivity.MATCH_ID, match_id);
			editDetailsIntent.putExtra(AddDetailsActivity.MATCH, matchFullTitle);
			editDetailsIntent.putExtra(AddDetailsActivity.DETAIL_ID, _id);
			startActivity(editDetailsIntent);
			return true;
		} else if (item.getItemId() == R.id.match_menu_startingEleven) {
			return true;
		} else {
			return super.onContextItemSelected(item);
		}

	}

	class DetailsBinder implements ViewBinder {

		private void setImageView(View view, int columnIndex, int thisSide) {
			ImageView imageView = (ImageView) view;
			int side = cursor.getInt(cursor.getColumnIndex(MatchData.DETAILS_C_SIDE));
			String icon = MatchData.ICONS[cursor.getInt(columnIndex)];
			int r = ShowMatchActivity.this.aek.getResources().getIdentifier(icon, "drawable", "com.aek.aekdroid");
			if (side == thisSide) {
				imageView.setImageResource(r);
				imageView.setVisibility(ImageView.VISIBLE);
			} else {
				imageView.setImageResource(r);
				imageView.setVisibility(ImageView.INVISIBLE);
			}

		}

		@Override
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

			if (view.getId() == R.id.detailIconAway) {
				line++;
				setImageView(view, columnIndex, 1);
				return true;
			} else if (view.getId() == R.id.detailIcon) {
				setImageView(view, columnIndex, 0);
				return true;
			} else if (view.getId() == R.id.detailMin) {
				String min = cursor.getString(columnIndex);
				String minShow = min + "'";
				String[] tokens = min.split("\\.");
				if (tokens.length > 1) {
					if (tokens[0].equals("45") || tokens[0].equals("90") || tokens[0].equals("105") || tokens[0].equals("120")) {
						minShow = tokens[0] + "'+";
					} else {
						minShow = tokens[0] + "'";
					}
				}
				((TextView) view).setText(minShow);
				return true;
			}

			return false;

		}
	}
}
